import tkinter as tk
from tkinter import filedialog, messagebox
from datetime import datetime
from PIL import Image, ImageTk
from tkcalendar import DateEntry
import json
import os
import re




def edit_task(card_frame, current_task_name, current_priority, current_due_date, current_image_path,window):
    try:
        edit_dialog = tk.Toplevel(window)
        edit_dialog.title("Edit Task")
        edit_dialog.geometry("400x300")

        task_name_var = tk.StringVar(value=current_task_name)
        priority_var = tk.StringVar(value=current_priority)
        due_date_var = tk.StringVar(value=current_due_date)
        image_path_var = tk.StringVar(value=current_image_path)

        task_name_label = tk.Label(edit_dialog, text="Task Name:")
        task_name_label.pack(pady=5)
        task_name_entry = tk.Entry(edit_dialog, textvariable=task_name_var)
        task_name_entry.pack(pady=5)

        priority_label = tk.Label(edit_dialog, text="Priority:")
        priority_label.pack(pady=5)
        priority_options = ["High", "Medium", "Low"]
        priority_menu = tk.OptionMenu(edit_dialog, priority_var, *priority_options)
        priority_menu.pack(pady=5)

        due_date_label = tk.Label(edit_dialog, text="Due Date (YYYY-MM-DD):")
        due_date_label.pack(pady=5)
        due_date_entry = DateEntry(edit_dialog, textvariable=due_date_var, date_pattern='yyyy-mm-dd')
        due_date_entry.pack(pady=5)

        def select_image():
            try:
                filename = filedialog.askopenfilename(title="Select Image", filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.gif")])
                if filename:
                    image_path_var.set(filename)
            except Exception as e:
                messagebox.showerror("Image Selection Error", str(e))

        def on_confirm(columns,frames,DATA_FILE):
            if not task_name_var.get() or not priority_var.get() or not due_date_var.get():
                messagebox.showerror("Input Error", "All fields are required.")
                return
            new_task_name = task_name_var.get()
            new_priority = priority_var.get()
            new_due_date = due_date_entry.get_date().strftime('%Y-%m-%d')
            new_image_path = image_path_var.get()

            for widget in card_frame.winfo_children():
                if isinstance(widget, tk.Label) and widget.cget('text').startswith("Task:"):
                    widget.config(text=f"Task: {new_task_name}")
                elif isinstance(widget, tk.Label) and widget.cget('text').startswith("Priority:"):
                    widget.config(text=f"Priority: {new_priority}")
                elif isinstance(widget, tk.Label) and widget.cget('text').startswith("Due Date:"):
                    widget.config(text=f"Due Date: {new_due_date}")
                elif isinstance(widget, tk.Label) and hasattr(widget, 'image'):
                    if new_image_path:
                        try:
                            img = Image.open(new_image_path)
                            img = img.resize((100, 100))
                            img = ImageTk.PhotoImage(img)
                            widget.config(image=img)
                            widget.image = img
                        except IOError:
                            messagebox.showerror("Error loading image", "The image file could not be opened or read.")
            edit_dialog.destroy()
            save_tasks(columns,frames,DATA_FILE)  # 保存任务数据到JSON文件

        confirm_button = tk.Button(edit_dialog, text="Confirm", command=on_confirm)
        confirm_button.pack(pady=10)
        select_image_button = tk.Button(edit_dialog, text="Select Image", command=select_image)
        select_image_button.pack(pady=5)

    except Exception as e:
        messagebox.showerror("Error editing task", str(e))

def save_tasks(columns,frames,DATA_FILE):
    try:
        tasks = []
        for col in columns:
            for child in frames[col].winfo_children():
                if isinstance(child, tk.Frame):
                    task_data = {
                        'name': '',
                        'priority': '',
                        'due_date': '',
                        'image_path': '',
                    }
                    for widget in child.winfo_children():
                        if isinstance(widget, tk.Label):
                            text = widget.cget('text')
                            if text.startswith('Task:'):
                                task_data['name'] = text.split(': ')[1]
                            elif text.startswith('Priority:'):
                                task_data['priority'] = text.split(': ')[1]
                            elif text.startswith('Due Date:'):
                                task_data['due_date'] = text.split(': ')[1]
                        elif isinstance(widget, tk.PhotoImage):
                            # 假设你有一个方式获取图片路径
                            task_data['image_path'] = widget.file
                    tasks.append(task_data)
        save_data(tasks,DATA_FILE)
    except Exception as e:
        messagebox.showerror("Error saving tasks", str(e))




def save_data(tasks,DATA_FILE):
    try:
        with open(DATA_FILE, 'w') as file:
            json.dump(tasks, file)
    except Exception as e:
        messagebox.showerror("Error saving data", str(e))